 var db = null;
 var isPG= false;
 
 function getDB(){
	 if(db == null){
		 db= window.openDatabase("activist", "1.0", "Test DB", 1000000);
		 db.transaction(function populateDB(tx) { 
					tx.executeSql('CREATE TABLE IF NOT EXISTS activity(id integer primary key autoincrement,name varchar(100),remoteid integer, sponsor varchar(100),phoneno varchar(100),lng varchar(50),lat varchar(50),desc varchar(500),updatedtime varchar(20));');
					tx.executeSql('CREATE TABLE IF NOT EXISTS activitydatetime(activityid integer,date varchar(10), time varchar(5));');
					tx.executeSql('CREATE TABLE IF NOT EXISTS activitypartner(activityid integer,name varchar(20), phoneno varchar(20));');
					tx.executeSql('CREATE TABLE IF NOT EXISTS user(id integer primary key autoincrement,name varchar(20), phoneno varchar(20),pwd varchar(30));');
					 
				}
				 , function(err){}, function successCB(){});
	 }
	 
	 else return db;
 }
 
 
function saveActivity(activity){
	var db = getDB();
	db.transaction(populateActivity, errorCB, successCB);
	function populateActivity(tx) {  
		tx.executeSql(insertQuery('activity',activity));
		 
	}

	function errorCB(err) {
	   	alert("Error processing SQL: "+err.code);
	}

	function successCB(tx, results) {
		var aid = results.insertId;
		db.transaction(function(tx){
			var adt = activity.dateTime;
			for ( var i in adt) {
				var obj = adt[i];
				obj.activityid = aid;
				tx.executeSql(insertQuery('activitydatetime',obj));
			}
			
			var partners = activity.partner;
			for ( var i in partners) {
				var obj = adt[i];
				obj.activityid = aid;
				tx.executeSql(insertQuery('activitypartner',obj));
			}
			
			tx.executeSql("insert into user(name,phoneno,pwd)select name,phoneno,substr(random(),-4) from activitypartner where activityid="+aid+" and phoneno not in (select phoneno from user) ");
		});
 
	}

	
}
function insertQuery(tableName,json){
	var query = "INSERT INTO "+tableName;
	var cols = "";
	var values = "";
	for ( var col in json) {
		if(typeof json[col] =='string'){
			cols = cols+","+col;
			values = values+",'"+json[col]+"'";
		}
	}
	return query+"("+cols.substr(1)+")values("+values.substr(1)+")";
}
function getAllActivities(){
	var json = {};
	var db = getDB();
	db.transaction(function (tx) {
		tx.executeSql("select date,activityid from activitydatetime order by date,time");
	}, function(err) {
	   	alert("Error processing SQL: "+err.code);
	}, function(tx, results) {
		var len = results.rows.length;
	    for (var i=0; i<len; i++){
	    	var date =  results.rows.item(i).date;
	    	var aid =  results.rows.item(i).activityid;
	    	if(!json[date]) 
	    		json[date] = new Array();
	    	json[date].push(activityid);
	    	
	    }

	});
	return json
}
